package com.ggy.ggyaiagent.rag;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.markdown.MarkdownDocumentReader;
import org.springframework.ai.reader.markdown.config.MarkdownDocumentReaderConfig;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class LoveAppDocumentLoader {
    private final ResourcePatternResolver resourcePatternResolver;

    public LoveAppDocumentLoader(ResourcePatternResolver resourcePatternResolver) {
        this.resourcePatternResolver = resourcePatternResolver;
    }

    /**
     * 加载所有的 markDown 资源，递归读取 document 目录下所有子文件夹中的 markdown 文件
     * @return
     */
    public List<Document> loadMarkDowns(){
        List<Document> allDocuments = new ArrayList<>();
        try{
            // 递归查找所有 document 下的 .md 文件
            Resource[] resources = resourcePatternResolver.getResources("classpath:document/**/*.md");
            for (Resource resource : resources) {
                String filename = resource.getFilename();
                String filePath = resource.getURL().getPath();
                // 获取所属文件夹名（如 旅游地点、景点信息等）
                String folderName = "";
                String[] pathParts = filePath.split("/document/");
                if (pathParts.length > 1) {
                    String subPath = pathParts[1];
                    String[] subParts = subPath.split("/");
                    if (subParts.length > 1) {
                        folderName = subParts[0];
                    }
                }
                // 提取文档的倒数第 3 个和倒数第 2 个字作为标签（如原逻辑）
                String status = filename.length() >= 6 ? filename.substring(filename.length() - 6, filename.length()-4) : "";
                // 创建配置类
                MarkdownDocumentReaderConfig config = MarkdownDocumentReaderConfig.builder()
                        .withHorizontalRuleCreateDocument(true)
                        .withIncludeCodeBlock(false)
                        .withIncludeBlockquote(false)
                        .withAdditionalMetadata("filename", filename)
                        .withAdditionalMetadata("status", status)
                        .withAdditionalMetadata("folder", folderName)
                        .build();
                // 读取数据
                MarkdownDocumentReader reader = new MarkdownDocumentReader(resource, config);
                allDocuments.addAll(reader.get());
            }
        } catch (Exception e) {
            log.error("Markdown 文件加载失败",e);
        }
        return allDocuments;
    }
}










